let fs = require('fs')
let EventEmitter = require('events')
class ReadStream extends EventEmitter {
  constructor(path, options={}) {
    this.path = path;
    this.flags = options.flags || 'r';
    this.mode = options.mode || 438
    this.start = options.start || 0
    this.end = options.end
    this.autoClose = options.autoClose || true
    this.highWaterMark = options.highWaterMark || 64*1024
    this.encoding = options.encoding || null
    this.pos = options.start || 0
    // 默认是非流动模式
    this.flowing = null

    // 打开文件
    this.open()
    // 这边为了用户监听data事件  我们就改成流动模式
    this.on('newListener', (type)=>{
      //
      if(type === 'data') {
        this.flowing = true
        this.read()
      }
    })
  }
  read() {
    // 默认第一次拿不到  等下触发了open事件才有
    if(typeof this.fd !== 'number') {
      return this.once('open', ()=>this.read())
    }
    let howMuchToRead = this.end ? Math.min((this.end - this.pos+1), this.highWaterMark) : this.highWaterMark
    let buffer = Buffer.alloc(howMuchToRead);  // highWaterMark多大就声明一个多大的buffer
    fs.read(this.fd, buffer, 0, buffer.length, this.pos, (err, bytesRead)=>{
      if(bytesRead > 0) {  // 
        this.pos += bytesRead
        this.emit('data', this.encoding ? buffer.toString(this.encoding) : buffer)
        if(this.flowing) {
          this.read()
        }
      }else{
        this.emit('end')
        if(this.autoClose) {
          fs.close(this.fd, ()=>{
            this.emit('close')
            this.flowing = null
          })
          
        }
      }
      
    });
  }

  open() {
    fs.open(this.path, this.flags, (err, fd)=>{
      if(err) {
        this.emit('error')
        return
      }
      this.emit('open', this.fd)
    })
  }
  pause() {
    this.flowing = false
  }
  resume() {
    this.flowing = true
    this.read()
  }
  pipe(ws) {
    this.on('data', (chunk) => {
      let flag = ws.write(chunk, (err)=>{
        console.log('chucuo l ', err)
      })
      if(!flag) {
        this.pause()
      }
    })
    
    ws.on('drain', ()=>{
      this.resume()
    })
  }
}

module.exports = ReadStream